package com.kefu.chat.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kefu.chat.model.ChatChannel;
import com.kefu.chat.service.ChatChannelService;
import com.kefu.chat.service.ChatWxService;
import com.kefu.common.controller.AbstractBaseController;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@RestController
@RequestMapping("chat/wx/{appId}")
public class ChatWxController extends AbstractBaseController {

    @Autowired
    private ChatWxService chatWxService;
    @Autowired
    private ChatChannelService chatChannelService;

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appId, String signature, String timestamp, String nonce, String echostr) {
        logger.info("接收到来自微信公众号的认证消息：[{},{}, {}, {}, {}]", appId, signature, timestamp, nonce, echostr);
        ChatChannel channel = chatChannelService.getFromAppId(appId);
        if (channel == null) return null;
        WxMpService wxMpService = chatWxService.getWxMpService(appId);
        if (wxMpService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return null;
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appId, @RequestBody String requestBody, String signature, String timestamp, String nonce, String openid, String encType, String msgSignature) {
        logger.info("接收微信公众号请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
        ChatChannel channel = chatChannelService.getFromAppId(appId);
        if (channel == null) return null;
//        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
//            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
//        }
        WxMpService wxMpService = chatWxService.getWxMpService(appId);
        WxMpXmlMessage inMessage = null;
        WxMpXmlOutMessage outMessage = null;
        String result = null;
        if (encType == null) {
            inMessage = WxMpXmlMessage.fromXml(requestBody);
        } else if ("aes".equalsIgnoreCase(encType)) {
            inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
        }
        logger.info("接收微信公众号请求解密:{},{}", appId, inMessage);
        if (inMessage != null) {
            if (inMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
                outMessage = chatWxService.eventHandle(appId, inMessage);
            } else {
                outMessage = chatWxService.msgHandle(appId, inMessage);
            }
        }
        if (encType == null && outMessage != null) {
            result = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType) && outMessage != null) {
            result = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }
        logger.info("公众号组装回复信息：{}", result);
        return result;
    }

}

